import loading from '@/components/xuan-loading/xuan-loading.vue'
import cLabel from "@/components/cat-label/cat-label.vue"
import personTree from '@/components/tree_03/tki-tree.vue';

export default {
	components: {
		loading,
		cLabel,
		personTree,
	},
	data() {
		return {
			identification:null,
			fromMsg: {
				fId: "", //传fid表示修改 不传表示新增
				userId: "", //当前登录人id
				userName: "", //当前登录人姓名
				fSamplereportid: "", //试验名称id
				fSamplereportname: "", //试验名称
				fCompletiondates: "", //预计完成日期
				fTestperson: "", //试验人
				fTestpersonid: "", //试验人id
				fTestnote: "", //备注
				fReportid: "",
			}, //参数
			header: {
				accessToken: "",
				projectId: "",
			}, //成都接口添加请求头
			SamplereportnameList: [], //试验名称
			PostSample: "", //生成样品编号
			PostReport: "", //生成报告编号
			SampleSxList: [], //获取检验对象属性
			registerList: {}, //保存取样登记数据
			TestMessage: {},
			flagNum: 0, //下拉框/时间表单  0可填  -1不可填
			timeYMD: null, //当前日期
			timeYmdHms: null,
			SyrjUrl: "", //公司接口动态前缀

			// loading样式
			width: '150rpx',
			height: '100rpx',
			shadeShow: false,
			backgroundColor: "transparent",
			themeColor: '#33CCCC',
			// loading样式

			// 树选人
			newData: null, //树选人最终选中结果
			selectParent1: true,
			multiple1: false,
			personList: [],
			flod1: true,
			// 树选人

			option: {},
			userInfo: {},
		};
	},
	onShow() {},
	onLoad(options) {
		var that = this;
		that.option = options;
		uni.getStorage({
			key: 'userInfo',
			success: function(res) {
				that.userInfo = JSON.parse(res.data);
			}
		})
		this.getDate();
		this.getInfoMsg(options.id)
		// this.timeing = new Date().getTime();

		// #ifdef APP-PLUS
		this.playVideo()
		uni.$on('submit-page', (data) => {
			that.clickNum()
		})
		// #endif
		// #ifdef H5
		this.appliance = 1
		// #endif

	},

	onUnload() {
		uni.$off('submit-page');
		// uni.$off('drawer-page');
	},
	onReady() {},

	// 返回
	onBackPress(event) {
		uni.navigateTo({
			url: "/pages/apply/sampleManage/collection/testing/index"
		});
		return true;
	},

	methods: {
		// // 材料编号带参数
		// otherFun(object) {
		// 	if (!!object) {
		// 		console.log("otherFun", object);
		// 	}
		// },
		// 详情接口
		getInfoMsg(id) {
			this.$http.getSampleWorkTestByFid({
				fId: id, //数据id
			}).then(res => {
				if (res.errcode == 0) {
					var that = this;
					this.SyrjUrl = res.data.SyrjUrl; //动态请求前缀
					that.fromMsg = res.data.lrCheckSample;
					that.TestMessage = res.data.TestMessage;
					that.getPerson(); //获取机构树
					that.getToken();
					if (that.fromMsg.fSamplereportname == null) {
						that.fromMsg.fSamplereportname = "";
					}
					if (that.fromMsg.fTestperson == null) {
						that.fromMsg.fTestperson = "";
					}
					if (that.fromMsg.fTestnote == null) {
						that.fromMsg.fTestnote = "";
					}
					if (that.fromMsg.fCompletiondates == "" || that.fromMsg.fCompletiondates == null) {
						that.fromMsg.fCompletiondates = this.timeYMD;
					}


				} else {
					uni.showToast({
						title: "获取详情数据失败",
						icon: 'none',
						duration: 2000
					});
				}
			}, (err) => {
				uni.showToast({
					title: "获取详情数据失败",
					icon: 'none',
					duration: 2000
				});
			});
		},


		// 下拉框---选择
		SamplereportnameChange(e) { //试验名称选择

			if (e.label == "==请选择==") {
				this.fromMsg.fSamplereportname = "";
				this.fromMsg.fSamplereportid = "";
				this.identification=""
			} else {
				this.fromMsg.fSamplereportname = e.label;
				this.fromMsg.fSamplereportid = e.value;
				this.identification=e.identification;
			}
		},
		TestpersonFocus() { //实验人展示弹框
			this.$refs.tkitrees._show();
		},
		poinblur() {},

		// 下拉框---选择

		// 保存/提交
		clickNum() {
			this.resultFrom()
		},
		resultFrom(data) {
			// 必填
			if (this.fromMsg.fSamplereportname == "" || this.fromMsg.fSamplereportname == undefined) {
				uni.showToast({
					title: '请选择试验名称',
					icon: 'none',
					duration: 2000
				});
				return false;
			} else if (this.fromMsg.fTestperson == "" || this.fromMsg.fTestperson == undefined) {
				uni.showToast({
					title: '请输入实验人',
					icon: 'none',
					duration: 2000
				});
				return false;
			} else if (this.fromMsg.fCompletiondates == "" || this.fromMsg.fCompletiondates == undefined) {
				uni.showToast({
					title: '请选择预计完后才能日期',
					icon: 'none',
					duration: 2000
				});
				return false;
			}
			this.getPostCreateNo("sample");
			this.getPostCreateNo("report");

		},
		//生成样品/报告编号--成都
		getPostCreateNo(text) {
			var data = {
				url: this.SyrjUrl,
				obj: {
					createType: text, //生成类型 （样品sample、报告report）
					organId: this.TestMessage.oBaseInfo.OrganID, //机构ID
					projectId: this.TestMessage.oBaseInfo.ProjectID, //项目ID
					companyId: this.TestMessage.oBaseInfo.CompanyID, //公司ID
					contractId: this.TestMessage.oBaseInfo.ContractID, //合同段ID
					identification: this.identification, //机构ID
					createDate: this.timeYMD, //机构ID
				}
			};
			this.$http.postCreateNo(data).then(res => {
				if (res.Result == 100) {
					if (text == "sample") {
						this.PostSample = res.Data; //生成样品编号
					} else {
						this.PostReport = res.Data; //生成报告编号
						this.getSampleSx();
					}
				} else {
					uni.showToast({
						title: "生成样品/报告编号获取数据失败"+res.Msg,
						icon: 'none',
						duration: 2000
					});
				}
			}, (err) => {
				uni.showToast({
					title: "生成样品/报告编号接口报错",
					icon: 'none',
					duration: 2000
				});
			});
		},
		//获取检验对象属性
		getSampleSx() {
			var data = {
				url: this.SyrjUrl,
				obj: {
					organId: this.TestMessage.oBaseInfo.OrganID, //机构ID
					testTypeId: this.TestMessage.oBaseInfo.TestTypeID, //检测项目ID
				}
			};

			this.$http.getSampleSxList(data).then(res => {
				if (res.Result == 100) {
					this.SampleSxList = res.Data;
					this.getRegister();
				} else {
					uni.showToast({
						title: '获取检验对象属性'+res.Msg,
						icon: 'none',
						duration: 2000
					});
				}
			}, (err) => {
				uni.showToast({
					title: "获取检验对象属性接口请求失败",
					icon: 'none',
					duration: 2000
				});
			})
		},
		//保存取样登记数据
		getRegister() {
			setTimeout(() => {
				this.SampleSxList.map((item) => {
					if (item.key == "取样地点") {
						item.val = this.fromMsg.fAddress;
					}
					if (item.key == "工程部位/用途") {
						item.val = this.fromMsg.fProjectlocation;
					}
					if (item.key == "样品描述") {
						item.val = this.fromMsg.fSamplemessage;
					}
					if (item.key == "强度等级" || item.key == "品种强度等级" || item.key == "品种等级") {
						item.val = this.fromMsg.fStrengthgrade;
					}
					if (item.key == "搅拌方式") {
						item.val = "人工+机械搅拌";
					}
					if (item.key == "试件尺寸") {
						item.val = this.fromMsg.fSpecimensize;
					}
					if (item.key == "养护条件") {
						item.val = "标准养护";
					}
					if (item.key == "养护龄期") {
						item.val = this.fromMsg.fSpecimenage;
					}
					if (item.key == "制件日期" || item.key == "生产日期") {
						item.val = this.fromMsg.fProductiondate;
					}
					if (item.key == "钢筋直径") {
						item.val = this.fromMsg.fDiameter;
					}
					if (item.key == "代表数量") {
						item.val = this.fromMsg.fDeputynum;
					}
					if (item.key == "生产厂家" || item.key == "厂家(产地)") {
						item.val = this.fromMsg.fManufacturer;
					}

					if (item.key == "批号" || item.key == "出厂编号" || item.key == "生产批号" || item.key ==
						"沥青标号") {

						item.val = this.fromMsg.fSampleno;
					}

					if (item.key == "规格型号") {
						item.val = this.fromMsg.fSamplespecs;
					}
					if (item.key == "产地") {
						item.val = this.fromMsg.fPlace;
					}

					if (item.key == "外加剂掺量") {
						item.val = this.fromMsg.fSamplenum;
					}
					if (item.key == "沥青种类" || item.key == "钢筋种类" || item.key == "混凝土种类" || item.key ==
						"砂浆种类" || item.key == "钢筋种类" || item.key == "沥青混合料类型") {
						item.val = this.fromMsg.fTesttype;
					}
					if (item.key == "搅拌方式") {
						item.val = this.fromMsg.fMixingmethod;
					}
					if (item.key == "养护条件") {
						item.val = this.fromMsg.fWarecondition;
					}
					if (item.key == "试验层位") {
						item.val = this.fromMsg.fTestlayer;
					}
					if (item.key == "级配类型") {
						item.val = this.fromMsg.fGradationtype;
					}
				});
				var data = {
					url: this.SyrjUrl,
					obj: {
						oBaseInfo: {
							ID: this.TestMessage.oBaseInfo.ID, //--主键ID
							SampleName: this.TestMessage.oBaseInfo.SampleName, //--样品名称
							Description: this.TestMessage.oBaseInfo.Description, //--样品描述
							ProjectPartAndUse: this.TestMessage.oBaseInfo.ProjectPartAndUse, //--工程部位用途
							ProductDate: this.TestMessage.oBaseInfo.ProductDate, //--制件日期    1
							SampleDate: this.TestMessage.oBaseInfo.SampleDate, //--取样日期
							// Others: null, //--检验对象属性
							// Others: this.SampleSxList, //--检验对象属性
							Others: JSON.stringify(this.SampleSxList), //--检验对象属性
							Register: this.TestMessage.oBaseInfo.Register, //--取样人ID
							RegisterNO: this.TestMessage.oBaseInfo.RegisterNO, //取样编号
							WitnessStatus: this.TestMessage.oBaseInfo.WitnessStatus, //--见证状态传入0
							SampleLongitude: this.TestMessage.oBaseInfo.SampleLongitude, //--取样经度
							SampleLatitude: this.TestMessage.oBaseInfo.SampleLatitude, //--取样纬度
							SampleLocation: this.TestMessage.oBaseInfo.SampleLocation, //--取样位置名称
							SubItemsID: this.TestMessage.oBaseInfo.SubItemsID, //--分部分项ID
							SubItemsNo: this.TestMessage.oBaseInfo.SubItemsNo, //--分部分项编号
							SubItemsName: this.TestMessage.oBaseInfo.SubItemsName, //--分部分项名称
							MaterialID: null, //--原材料ID
							MaterialNo: null, //--原材料编号
							TestTypeID: this.TestMessage.oBaseInfo.TestTypeID, //--样品类型ID（对应检测项目ID）
							SampleIdentification: this.TestMessage.oBaseInfo
								.SampleIdentification, //--样品标识(对应样品分类值)
							CompanyID: this.TestMessage.oBaseInfo.CompanyID, //--公司ID
							ProjectID: this.TestMessage.oBaseInfo.ProjectID, //--项目ID
							OrganID: this.TestMessage.oBaseInfo.OrganID, //--机构ID
							ContractID: this.TestMessage.oBaseInfo.ContractID, //--施工标段ID
							CreateTime: this.TestMessage.oBaseInfo.CreateTime, //--创建时间
							TestAge: this.TestMessage.oBaseInfo.TestAge, //--龄期
							StorageLocation: this.TestMessage.oBaseInfo.StorageLocation, //--存放位置
						},

						oTestList: this.TestMessage.oTestList,
						oPhotoList: this.TestMessage.oPhotoList,

						oAppFlow: this.TestMessage
							.oAppFlow, //--oAppFlow为2时，参数必传，为1时不传---默认为1 ，2取样登记后就直接生成报告编号
						oUserId: Number(this.TestMessage.oUserId), //--oAppFlow为2时，参数必传，为1时不传---用户Id
						oSampleNo: this.PostSample, //--oAppFlow为2时，参数必传，为1时不传---样品编号
						oTestRoomId: this.TestMessage.oTestRoomId, //--oAppFlow为2时，参数必传，为1时不传---试验室Id
						oReportId: this.fromMsg.fSamplereportid, //--oAppFlow为2时，参数必传，为1时不传--报告Id
						oTestDate: this.fromMsg.fCompletiondates, //--oAppFlow为2时，参数必传，为1时不传---试验日期
						oReportNo: this.PostReport, //--oAppFlow为2时，参数必传，为1时不传---报告编号
						oIsCure: this.TestMessage.oIsCure, //--必传---是否养护
						oInTime: this.TestMessage.oInTime, //--oIsCure为true时，参数必传，为false时不传--入箱时间
						oYhStorageLocation: this.TestMessage
							.oYhStorageLocation, //--oIsCure为true时，参数必传，为false时不传---存放位置
						oStorager: this.TestMessage.oStorager, //--oIsCure为true时，参数必传，为false时不传---存放人

					}
				};

				this.$http.register(data).then(res => {

					if (res.Result == 100) {
						this.registerList = res.Data;
						this.saveFun(this.registerList);
					} else {
						uni.showToast({
							title: "获取保存取样登记"+res.Msg,
							icon: 'none',
							duration: 2000
						});
					}
				}, (err) => {
					uni.showToast({
						title: "获取保存取样登记数据接口请求失败",
						icon: 'none',
						duration: 2000
					});
				})
			}, 300)
		},
		testperson(e) {
			console.log(e);
		},
		// 保存接口
		saveFun(data) {
			if (this.newData == null) {
				this.fromMsg.fTestpersonid = "";
			} else {
				if (this.fromMsg.fTestperson != this.newData.fStaffName) {
					this.fromMsg.fTestpersonid = "";
				}
			}
			var saveData = {
				fId: this.fromMsg.fId, //传fid表示修改 不传表示新增
				userId: this.userInfo.userId, //当前登录人id
				userName: this.userInfo.realName, //当前登录人姓名
				fSamplereportid: this.fromMsg.fSamplereportid, //试验名称
				fSamplereportname: this.fromMsg.fSamplereportname, //试验名称id
				fCompletiondates: this.fromMsg.fCompletiondates, //预计完成日期
				fTestperson: this.fromMsg.fTestperson, //试验人
				fTestpersonid: this.fromMsg.fTestpersonid, //试验人id
				fTestnote: this.fromMsg.fTestnote, //备注
				fSampleassignnostr: this.PostSample, //样品编号
				fSamplereportnostr: this.PostReport, //报告编号
				fReportid: data.ReportId, //报告id
				fSampleid: data.SampleId, //样品id
			};
			this.$http.saveSampleCollection(saveData).then(res => {

				if (res.errcode == 0) {
					this.$refs.loadings.open();
					setTimeout(() => {
						uni.showToast({
							title: "保存成功",
							icon: 'none',
							duration: 2000
						});
						let that = this
						uni.redirectTo({
							url: "/pages/apply/sampleManage/collection/testing/index?Inv=" +
								"4",
							success: () => {
								that.click = false
								that.$refs.loadings.close();
							}
						})
					}, 1500)
				} else {

					this.$refs.loadings.close();
					uni.showToast({
						title: "保存失败",
						icon: 'none',
						duration: 2000
					});

				}

			}, (err) => {
				uni.showToast({
					title: "保存接口失败",
					icon: 'none',
					duration: 2000
				});
			})

		},
		// 保存/提交



		// 原生窗体按钮显示
		playVideo() {
			let subNVue = uni.getSubNVueById('fieldSampling')
			subNVue.show()
		},
		// 获取当前日期
		getDate() {
			var time = new Date();
			const y = time.getFullYear();
			const m = (time.getMonth() + 1 + "").padStart(2, "0");
			const d = (time.getDate() + "").padStart(2, "0");
			const hh = (time.getHours() + "").padStart(2, "0");
			const mm = (time.getMinutes() + "").padStart(2, "0");
			const ss = (time.getSeconds() + "").padStart(2, "0");
			var timer = `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
			var timing = `${y}-${m}-${d}`;
			this.timeYMD = timing;
			this.timeYmdHms = timer;
		},
		// 成都
		// 获取Token
		getToken() {

			var data = {
				url: this.SyrjUrl,
				obj: {
					companyId: this.TestMessage.oBaseInfo.CompanyID,
					projectId: this.TestMessage.oBaseInfo.ProjectID,
					userId: this.TestMessage.oUserId
				}
			};
			this.$http.apiTokenBuild(data).then(res => {
				if (res.Result == 100) {
					this.header = {
						accessToken: res.Data.Token,
						projectId: this.TestMessage.oBaseInfo.ProjectID,
					};
					uni.setStorageSync('headerToken', this.header);
					this.getPostTestList(); //试验名称下拉框list
				} else {
					uni.showToast({
						title: "Token获取数据失败"+res.Msg,
						icon: 'none',
						duration: 2000
					});
				}
			}, (err) => {
				uni.showToast({
					title: "获取Token接口报错",
					icon: 'none',
					duration: 2000
				});
			})
		},
		//试验名称List
		getPostTestList() {
			var data = {
				url: this.SyrjUrl,
				obj: {
					identfication: this.TestMessage.oBaseInfo.SampleIdentification, //样品标识
					organId: this.TestMessage.oBaseInfo.OrganID, //机构ID
					companyId: this.TestMessage.oBaseInfo.CompanyID, //公司ID
					testTypeId: this.TestMessage.oBaseInfo.TestTypeID, //检测项目ID
				}
			};

			this.$http.postTestList(data).then(res => {
				if (res.Result == 100) {
					this.SamplereportnameList = [{
						value: "==请选择==",
						label: "==请选择==",
					}];
					res.Data.map(item => {
						this.SamplereportnameList.push({
							value: item.val, //id
							label: item.key, //name
							identification:item.identification
						});
					})
				} else {
					uni.showToast({
						title: "试验名称获取数据失败"+res.Msg,
						icon: 'none',
						duration: 2000
					});
				}
			}, (err) => {
				uni.showToast({
					title: "试验名称接口报错",
					icon: 'none',
					duration: 2000
				});
			});
		},
		// 成都



		// 树选人
		getPerson() { //获取机构树
			this.$http.getUserCompanyTreeList({
					companyId: this.userInfo.companyId,
					userId: this.userInfo.userId,
				})
				.then((res) => {
					if (res.errcode == 0) {
						var treeData = this.tranListToTreeData(
							res.data.userCompanyTreeList
						);
						this.personList = treeData; //机构树
					} else {
						uni.showToast({
							title: "获取机构树失败",
							icon: 'none',
							duration: 2000
						});
						return false;
					}
				})
		},
		tranListToTreeData(data) {
			let result = [];
			if (!Array.isArray(data)) {
				return result;
			}
			// 清除已存在的children 重新赋值
			data.forEach((item) => {
				delete item.children;
			});

			let map = {};
			data.forEach((item) => {
				map[item.fCompanyid] = item;
			});

			data.forEach((item) => {
				let parent = map[item.fParentid];
				if (parent) {
					(parent.children || (parent.children = [])).push(item);
				} else {
					result.push(item);
				}
			});
			return result;
		},
		treeConfirms(data) { // 确定回调事件
			this.newData = data[0];
			this.fromMsg.fTestpersonid = data[0].fId; //试验人id
			this.fromMsg.fTestperson = data[0].fStaffName; //试验人名称
		},

		treeCancels(e) { // 取消回调事件
		},
		// 树选人
	}
}
